<template>
  <div>
    <div class="caliberTable">
      <el-row>
        <el-col style="margin-right: 10px" :span="24" class="content-left">
          <el-row class="handleBox">
            <el-col :span="18">
              <template>
                <el-button type="normal" @click="addCaliber">新增</el-button>
                <el-button type="normal" @click="editCaliber">编辑</el-button>
                <el-button type="normal" @click="handleDelete">删除</el-button>
              </template>
            </el-col>
            <el-col :span="6">
              <div class="handleIconBox">
                <el-popover
                  placement="bottom"
                  trigger="click"
                  popper-class="icon_porper"
                >
                  <div class="export_porper">
                    <!-- 导出操作区域 -->
                    <el-button @click="exportExcel">导出</el-button>
                  </div>
                  <i
                    class="iconfont icon-export"
                    title="导出"
                    slot="reference"
                  ></i>
                </el-popover>
                <!-- 导入 -->
                <el-popover
                  placement="bottom"
                  trigger="click"
                  popper-class="icon_porper"
                >
                  <div class="import_porper">
                    <!-- 导入操作区域 -->

                    <el-upload
                      accept=".xls, .xlsx"
                      ref="upload"
                      :multiple="false"
                      :before-upload="beforeUpload"
                      :show-file-list="false"
                      action
                      :limit="1"
                      :http-request="uploadFile"
                    >
                      <el-button>导入</el-button>
                    </el-upload>
                  </div>
                  <i
                    class="iconfont icon-import"
                    title="导入"
                    slot="reference"
                  ></i>
                </el-popover>
                <el-popover
                  placement="bottom"
                  trigger="click"
                  popper-class="icon_porper"
                >
                  <div class="search_porper">
                    <el-form
                      :model="searchForm"
                      ref="searchForm"
                      label-width="90px"
                      label-position="left"
                      size="mini"
                    >
                      <el-form-item label="生效日期">
                        <el-date-picker
                          v-model="searchForm.effectDt"
                          type="date"
                          style="width: 150px"
                          placeholder="选择日期"
                          :clearable="false"
                        ></el-date-picker>
                      </el-form-item>
                      <el-form-item label="口径编号：">
                        <el-input
                          v-model.trim="searchForm.caliberNo"
                          style="width: 150px"
                        ></el-input>
                      </el-form-item>
                      <el-form-item label="口径属性">
                        <el-select
                          v-model="searchForm.caliberDefAttr"
                          style="width: 150px"
                          placeholder="请选择"
                        >
                          <el-option
                            v-for="item in caliberDefAttrOptions"
                            :key="item.key"
                            :label="item.value"
                            :value="item.key"
                          ></el-option>
                        </el-select>
                      </el-form-item>

                      <el-form-item label="口径名称">
                        <el-input
                          style="width: 150px"
                          placeholder="请输入"
                          v-model="searchForm.caliberName"
                        ></el-input>
                      </el-form-item>
                    </el-form>
                    <div style="text-align: center; padding: 10px">
                      <el-button
                        size="mini"
                        @click="(searchForm.page = 1), searchFunc()"
                        >查询</el-button
                      >
                      <el-button size="mini" @click="searchClear"
                        >重置</el-button
                      >
                    </div>
                  </div>
                  <i
                    class="iconfont icon-sousuo"
                    title="搜索"
                    slot="reference"
                  ></i>
                </el-popover>
                <el-popover
                  placement="bottom"
                  width="150"
                  trigger="click"
                  popper-class="icon_porper"
                >
                  <div class="operation_checkbox">
                    <el-checkbox-group v-model="checkList">
                      <el-checkbox
                        v-for="item in textData"
                        :label="item.label"
                        :key="item.prop"
                        >{{ item.label }}
                      </el-checkbox>
                    </el-checkbox-group>
                  </div>
                  <i
                    class="iconfont icon-liebiaoshezhi"
                    title="列表设置"
                    slot="reference"
                  ></i>
                </el-popover>
              </div>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <el-table
        ref="multipleTable"
        :data="tableData"
        @row-click="rowClick"
        style="width: 100%"
      >
        <el-table-column
          width="55"
          type="selection"
          
        ></el-table-column>
        <el-table-column
          v-for="(item, key) in showData"
          align="center"
          :key="key"
          :prop="item.prop"
          :label="item.label"
          :show-overflow-tooltip="true"
          :render-header="item.render"
          :sortable="item.sortable"
          :formatter="item.formatter"
          :width="item.width"
          :min-width="item.minwidth"
        ></el-table-column>
      </el-table>
    </div>
    <pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="searchForm.page"
      @refresh="searchFunc"
      :page-size="searchForm.size"
      :total="total"
    ></pagination>
    <!-- 新增弹框 -->
    <addCaliber
      :addCaliberVisible="addCaliberVisible"
      :cancelCaliberM="cancelCaliberM"
      :addCaliberM="addCaliberM"
      :closeAddDialog="closeAddDialog"
      ref="addCaliberData"
    ></addCaliber>
    <!-- 编辑弹框 -->
    <editCaliber
      :editCaliberVisible="editCaliberVisible"
      :editCancelCaliberM="editCancelCaliberM"
      :editCaliberM="editCaliberM"
      :editCloseAddDialog="editCloseAddDialog"
      ref="editCaliberData"
    ></editCaliber>
  </div>
</template>
<script>
import { DatasCenter } from "@/api/index";
import moment from "moment";
import editCaliber from "./editCaliber.vue";
import addCaliber from "./addCaliber.vue";
import { dateFormat } from "@/lib/util.js";
export default {
  name: "caliberTable",
  components: {
    addCaliber,
    editCaliber,
  },
  data() {
    return {
      checkList: [],
      excelFile: "",
      caliberNo: "",
      addCaliberForm: {
        effectDt: "",
        invalidDt: "",
        caliberNo: "",
        caliberName: "",
        caliberDesc: "",
        caliberDefAttr: "",
        caliberDefFilter: "",
        caliberDefFilterId: "",
        memo: "",
        uuid: "",
      }, // 新增口径数据
      // text: "确定要删除所选数据？",
      id: "", // 口径id
      centerDialogVisible: false,
      addCaliberVisible: false,
      editCaliberVisible: false,
      caliberDefAttrOptions: [],
      // 第几页
      page: 1,
      // 页面展示个数
      size: 15,
      // 总数
      total: 0,
      searchForm: {
        effectDt: moment().format("YYYY-MM-DD"),
        caliberNo: "",
        caliberDefAttr: "",
        caliberName: "",
        page: 1,
        size: 15,
      },
      textData: [
        {
          prop: "effectDt",
          label: "生效日期",
        },
        {
          prop: "invalidDt",
          label: "失效日期",
        },
        {
          prop: "caliberNo",
          label: "口径编号",
        },
        {
          prop: "caliberName",
          label: "口径名称",
        },
        {
          prop: "caliberDefAttr",
          label: "口径属性",
        },
        {
          prop: "caliberDefFilter",
          label: "口径属性范围",
          formatter: (row) => {
            if (row.caliberDefFilter) {
              let caliberDefFilter = row.caliberDefFilter.split(",");
              console.log(
                caliberDefFilter,
                caliberDefFilter.length,
                "caliberDefFilter"
              );
              if (caliberDefFilter.length > 10) {
                let arr = caliberDefFilter.slice(0, 10);
                return arr.join(",") + ",...";
              } else {
                return caliberDefFilter.join(",");
              }
            }
          },
        },
        {
          prop: "caliberDesc",
          label: "口径描述",
        },
        {
          prop: "memo",
          label: "备注",
        },
        {
          prop: "modifyOperNo",
          label: "修订人",
          formatter: (row) => {
            if (row.modifyOperNo) {
              return row.modifyOperNo;
            } else {
              return "-";
            }
          },
        },
        {
          prop: "modifyTime",
          label: "修订日期",
          formatter: (row) => {
            if (row.modifyTime) {
              return moment(row.modifyTime).format("YYYY-MM-DD HH:mm:ss"); // 24小时制
            } else {
              return "-";
            }
          },
        },
      ],

      //
      tableData: [],
    };
  },
  created() {
    this.searchFunc();
    this.caliberDefAttrOption();
    this.checkListInit();
  },
  computed: {
    // 展示字段
    showData() {
      let arr = this.textData.map((v) => {
        return v.label;
      });
      let valArr = [],
        showData = [];
      // 选中的字段排序
      arr.forEach((element) => {
        let flag = false;
        this.checkList.forEach((e) => {
          if (e == element) {
            flag = true;
          }
        });
        if (flag) {
          valArr.push(element);
        }
      });
      // 控制表列隐藏显示
      for (let i = 0; i < this.checkList.length; i++) {
        for (let j = 0; j < this.textData.length; j++) {
          if (this.textData[j].label == valArr[i]) {
            let item = { ...this.textData[j] };
            showData.push(item);
          }
        }
      }
      return showData;
    },
  },
  methods: {
    checkListInit() {
      this.checkList = this.textData.map((v) => {
        return v.label;
      });
    },
    rowClick(row) {
      this.$refs.multipleTable.clearSelection();
      this.$refs.multipleTable.toggleRowSelection(row, true);
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.searchForm.size = val;
      this.searchFunc();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.searchForm.page = val;
      this.searchFunc();
    },
    searchClear() {
      for (const key in this.searchForm) {
        this.searchForm[key] = "";
      }
      this.searchForm.page = 1;
      this.searchForm.size = 15;
    },
    // 上传文件
    beforeUpload(file) {
      let name = file.name;
      let type = name.substring(name.indexOf("."), name.length);
      if (type === ".xls" || type === ".xlsx") {
        return true;
      }
      this.$message({
        message: "只能选择xls或者xlsx格式的文件上传",
        type: "warning",
        showClose: true,
      });
      return false;
    },
    // 上传文件
    uploadFile(item) {
      this.excelFile = item.file;
      let form = new FormData();
      // 文件对象
      form.append("uploadfile", this.excelFile);
      var that = this;
      DatasCenter.impCaliber(form)
        .then((response) => {
          if (response.code == 200) {
            that.$message({
              type: "success",
              message: "文件：" + this.excelFile.name + "上传成功",
            });
            that.$refs.upload.clearFiles();
            that.searchFunc();
          } else {
            that.$message({
              type: "error",
              message: response.message,
            });
            that.$refs.upload.clearFiles();
          }
        })
        .catch(function () {
          that.$message({
            type: "warning",
            message: "文件内容与模板不相符，导入失败",
          });
        });
    },
    // 导出
    exportExcel() {
      if (this.searchForm.effectDt) {
        this.searchForm.effectDt = dateFormat(this.searchForm.effectDt);
      }
      let forms = {
        effectDt: this.searchForm.effectDt,
        caliberNo: this.searchForm.caliberNo,
        caliberDefAttr: this.searchForm.caliberDefAttr,
        caliberName: this.searchForm.caliberName,
        page: 1,
        size: 999999,
      };
      DatasCenter.expCaliber(forms)
        .then((response) => {
          if (response) {
            var filename = decodeURI(
              response.headers["content-disposition"]
            ).split("=")[1];
            let contenttype =
              filename.substring(filename.lastIndexOf("."), filename.length) ===
              "xlsx"
                ? "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
                : "application/vnd.ms-excel;charset=utf-8";
            var blob = new Blob([response.data], {
              type: contenttype,
            });
            if (window.navigator.msSaveOrOpenBlob) {
              navigator.msSaveBlob(blob, filename);
            } else {
              var downloadElement = document.createElement("a");
              var href = window.URL.createObjectURL(blob); //创建下载的链接
              downloadElement.href = href;
              downloadElement.download = filename; //下载后文件名
              document.body.appendChild(downloadElement);
              downloadElement.click(); //点击下载
              document.body.removeChild(downloadElement); //下载完成移除元素
              window.URL.revokeObjectURL(href); //释放掉blob对象
            }
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    // 默认 条件查询
    searchFunc() {
      this.page = 1;
      this.getPageCaliberList();
    },
    // 获取口径列表
    getPageCaliberList() {
      if (this.searchForm.effectDt) {
        this.searchForm.effectDt = dateFormat(this.searchForm.effectDt);
      }
      let form = {
        sort: "modifyTime",
        order: "desc",
        page: this.page,
        size: this.size,
        effectDt: this.searchForm.effectDt,
        caliberNo: this.searchForm.caliberNo,
        caliberDefAttr: this.searchForm.caliberDefAttr,
        caliberName: this.searchForm.caliberName,
      };
      DatasCenter.findPageCaliber(form).then((res) => {
        this.tableData = res.data;
        this.total = res.count;
        for (var i = 0; i < this.tableData.length; i++) {
          this.tableData[i].effectDt = dateFormat(this.tableData[i].effectDt);
          if (this.tableData[i].invalidDt) {
            this.tableData[i].invalidDt = dateFormat(
              this.tableData[i].invalidDt
            );
          }
          if (this.tableData[i].modifyTime) {
            this.tableData[i].modifyTime = dateFormat(
              this.tableData[i].modifyTime
            );
          }
        }
      });
    },
    caliberDefFilterFormat(row) {
      if (row.caliberDefFilter) {
        let caliberDefFilter = row.caliberDefFilter.split(",");
        console.log(
          caliberDefFilter,
          caliberDefFilter.length,
          "caliberDefFilter"
        );
        if (caliberDefFilter.length > 10) {
          let arr = caliberDefFilter.slice(0, 10);
          return arr.join(",") + ",...";
        } else {
          return caliberDefFilter.join(",");
        }
      }
    },
    // 点击新增按钮
    addCaliber() {
      this.addCaliberVisible = true;
      this.$refs["addCaliberData"].addForm = {};
      this.$refs["addCaliberData"].getCaliberDefAttrOptions();
      this.$refs["addCaliberData"].getFlexibleModelAttr();
      this.$refs["addCaliberData"].selectDefAttrShow = true;
      this.$refs["addCaliberData"].treeShow = false;
      this.$refs["addCaliberData"].gridShow = false;
      this.$refs["addCaliberData"].caliberGridDataShow = false;

      this.$nextTick(() => {
        this.$refs["addCaliberData"].$refs.addForm.clearValidate();
      });
    },
    closeAddDialog() {
      this.addCaliberVisible = false;
    },
    cancelCaliberM() {
      this.addCaliberVisible = false;
    },
    // 新增确定
    addCaliberM() {
      this.$refs["addCaliberData"].$refs.addForm.validate((valid) => {
        if (valid) {
          // 获取保存接口
          // 格式话时间
          if (this.$refs["addCaliberData"].addForm.invalidDt) {
            this.$refs["addCaliberData"].addForm.invalidDt = dateFormat(
              this.$refs["addCaliberData"].addForm.invalidDt
            );
          }
          this.$refs["addCaliberData"].addForm.effectDt = dateFormat(
            this.$refs["addCaliberData"].addForm.effectDt
          );
          // 格式化选择的treeID

          if (
            this.$refs["addCaliberData"].addForm.caliberDefFilterId instanceof
            Array
          ) {
            this.$refs[
              "addCaliberData"
            ].addForm.caliberDefFilterId = this.$refs[
              "addCaliberData"
            ].addForm.caliberDefFilterId.join(",");
          }
          // 下拉框
          if (!this.$refs["addCaliberData"].selectDefAttrShow) {
            this.$refs[
              "addCaliberData"
            ].addForm.caliberDefFilterId = this.$refs[
              "addCaliberData"
            ].addForm.caliberDefFilters;
          }
          // 未选择口径属性范围
          if (!this.$refs["addCaliberData"].addForm.caliberDefFilterId) {
            this.$message({
              showClose: true,
              message: "请选择口径范围",
              type: "error",

              center: true,
            });
            return;
          }
          let params = {
            effectDt: this.$refs["addCaliberData"].addForm.effectDt,
            invalidDt: this.$refs["addCaliberData"].addForm.invalidDt,
            caliberNo: this.$refs["addCaliberData"].addForm.caliberNo,
            caliberName: this.$refs["addCaliberData"].addForm.caliberName,
            caliberDesc: this.$refs["addCaliberData"].addForm.caliberDesc,
            caliberDefAttr: this.$refs["addCaliberData"].addForm.caliberDefAttr,
            caliberDefFilter: this.$refs["addCaliberData"].addForm
              .caliberDefFilterId,
            memo: this.$refs["addCaliberData"].addForm.memo,
            uuid: "",
          };
          DatasCenter.checkUniqueCaliber(params).then((res) => {
            if (res.code == 200) {
              if (res.data == true) {
                this.addCaliberConfirm();
              } else {
                this.$message({
                  showClose: true,
                  message: "此数据已存在",
                  type: "error",
                });
              }
            } else {
              this.$message({
                showClose: true,
                message: res.message,
                type: "error",
              });
            }
          });
        }
      });
    },
    editCloseAddDialog() {
      this.editCaliberVisible = false;
    },
    // 新增保存
    addCaliberConfirm() {
      let params = {
        effectDt: this.$refs["addCaliberData"].addForm.effectDt,
        invalidDt: this.$refs["addCaliberData"].addForm.invalidDt,
        caliberNo: this.$refs["addCaliberData"].addForm.caliberNo,
        caliberName: this.$refs["addCaliberData"].addForm.caliberName,
        caliberDesc: this.$refs["addCaliberData"].addForm.caliberDesc,
        caliberDefAttr: this.$refs["addCaliberData"].addForm.caliberDefAttr,
        caliberDefFilter: this.$refs["addCaliberData"].addForm
          .caliberDefFilterId,
        memo: this.$refs["addCaliberData"].addForm.memo,
        uuid: "",
      };
      DatasCenter.saveCaliber(params).then((res) => {
        if (res.code == 200) {
          this.$message({
            showClose: true,
            message: "数据保存成功",
            type: "success",
            center: true,
          });
          (this.addCaliberVisible = false),
            // 更新数据列表
            this.searchFunc();
        }
      });
    },
    // 编辑
    editCaliber() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据进行修改");
      }
      let val = selection[0];
      this.$refs["editCaliberData"].datas = val;
      this.$refs["editCaliberData"].getCaliberDefAttrOptions();
      this.$refs["editCaliberData"].getFlexibleModelAttr();
      this.$refs["editCaliberData"].getEditEcho();
      this.editCaliberVisible = true;
      this.$refs["editCaliberData"].selectDefAttrShow = true;
      this.$refs["editCaliberData"].treeShow = false;
      this.$refs["editCaliberData"].gridShow = false;
      this.$refs["editCaliberData"].caliberGridDataShow = false;
      //清除表单校验
      this.$nextTick(() => {
        this.$refs["editCaliberData"].$refs.editForm.clearValidate();
      });
      this.$refs[
        "editCaliberData"
      ].editForm.caliberDefAttr = this.caliberDefAttrOptions.find(
        (item) => item.value == val.caliberDefAttr
      ).key;
    },
    // 编辑保存
    editCaliberM() {
      this.$refs["editCaliberData"].$refs.editForm.validate((valid) => {
        if (valid) {
          // 获取保存接口
          // 格式话时间
          if (this.$refs["editCaliberData"].editForm.invalidDt) {
            this.$refs["editCaliberData"].editForm.invalidDt = dateFormat(
              this.$refs["editCaliberData"].editForm.invalidDt
            );
          }
          this.$refs["editCaliberData"].editForm.effectDt = dateFormat(
            this.$refs["editCaliberData"].editForm.effectDt
          );
          // 格式化选择的treeID
          if (
            this.$refs["editCaliberData"].editForm.caliberDefFilterId instanceof
            Array
          ) {
            this.$refs[
              "editCaliberData"
            ].editForm.caliberDefFilterId = this.$refs[
              "editCaliberData"
            ].editForm.caliberDefFilterId.join(",");
          }
          // 下拉框
          if (!this.$refs["editCaliberData"].selectDefAttrShow) {
            this.$refs[
              "editCaliberData"
            ].editForm.caliberDefFilterId = this.$refs[
              "editCaliberData"
            ].editForm.caliberDefFilters;
          }
          // 未选择口径属性范围
          if (!this.$refs["editCaliberData"].editForm.caliberDefFilterId) {
            this.$message({
              showClose: true,
              message: "请选择口径属性范围",
              type: "error",

              center: true,
            });
            return;
          }
          let params = {
            effectDt: this.$refs["editCaliberData"].editForm.effectDt,
            invalidDt: this.$refs["editCaliberData"].editForm.invalidDt,
            caliberNo: this.$refs["editCaliberData"].editForm.caliberNo,
            caliberName: this.$refs["editCaliberData"].editForm.caliberName,
            caliberDesc: this.$refs["editCaliberData"].editForm.caliberDesc,
            caliberDefAttr: this.$refs["editCaliberData"].editForm
              .caliberDefAttr,
            caliberDefFilter: this.$refs["editCaliberData"].editForm
              .caliberDefFilterId,
            memo: this.$refs["editCaliberData"].editForm.memo,
            uuid: this.$refs["editCaliberData"].editForm.uuid,
          };
          DatasCenter.checkUniqueCaliber(params).then((res) => {
            if (res.code == 200) {
              if (res.data == true) {
                this.editCaliberConfirm();
              } else {
                this.$message({
                  showClose: true,
                  message: "此数据已存在",
                  type: "error",
                });
              }
            } else {
              this.$message({
                showClose: true,
                message: res.message,
                type: "error",
              });
            }
          });
        }
      });
    },
    // 编辑保存确定
    editCaliberConfirm() {
      let params = {
        effectDt: this.$refs["editCaliberData"].editForm.effectDt,
        invalidDt: this.$refs["editCaliberData"].editForm.invalidDt,
        caliberNo: this.$refs["editCaliberData"].editForm.caliberNo,
        caliberName: this.$refs["editCaliberData"].editForm.caliberName,
        caliberDesc: this.$refs["editCaliberData"].editForm.caliberDesc,
        caliberDefAttr: this.$refs["editCaliberData"].editForm.caliberDefAttr,
        caliberDefFilter: this.$refs["editCaliberData"].editForm
          .caliberDefFilterId,
        memo: this.$refs["editCaliberData"].editForm.memo,
        uuid: this.$refs["editCaliberData"].editForm.uuid,
      };
      DatasCenter.saveCaliber(params).then((res) => {
        if (res.code == 200) {
          this.$message({
            message: "数据修改成功",
            type: "success",
          });
          (this.editCaliberVisible = false),
            // 更新数据列表
            this.searchFunc();
        }
      });
    },
    editCancelCaliberM() {
      this.editCaliberVisible = false;
    },
    // 删除
    handleDelete() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length < 1) {
        return this.$message.warning("请选择要删除的数据");
      }
      this.$confirm("你确认要删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let params = {
            ids: selection.map((v) => v.uuid),
            caliberNos: selection.map((v) => v.caliberNo),
          };
          DatasCenter.removeCaliber(params)
            .then((res) => {
              if (res.code == 200) {
                this.searchFunc();
              } else {
                this.$message.error(res.message);
              }
            })
            .catch((err) => {});
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 获取口径属性
    caliberDefAttrOption() {
      DatasCenter.findCaliberAttrIndexBase().then((res) => {
        this.caliberDefAttrOptions = res.data;
      });
    },
    // 重置
    reset() {
      this.searchForm = {};
      this.$set(this.searchForm, "effectDt", moment().format("YYYY-MM-DD"));
    },
    // 处理页面sizes
    handlePaginationSizes(value) {
      this.size = Number(value);
      this.getPageCaliberList();
    },

    //处理当前页
    handlePaginationCurrent(value) {
      this.page = Number(value);
      this.getPageCaliberList();
      window.removeEventListener("keydown", function () {});
    },

    // 处理刷新回调
    handlePaginationRefresh() {
      this.getPageCaliberList();
    },
  },
};
</script>

<style lang="scss" scoped>
</style>